import { useUserStore } from "@/pinia/stores/user"
import { isArray } from "@@/utils/validate"
import { RouteRecordRaw } from "vue-router"

/** 全局权限判断函数，和权限指令 v-permission 功能类似 */
export function checkPermission(permissionRoles: string[]): boolean {
  if (isArray(permissionRoles) && permissionRoles.length > 0) {
    const { roles } = useUserStore()
    return roles.some(role => permissionRoles.includes(role))
  } else {
    console.error("参数必须是一个数组且长度大于 0，参考：checkPermission(['admin', 'editor'])")
    return false
  }
}

// 2. 检查路径是否存在
export function isPathExist(RoutePaths: string[], targetPath: string): boolean {
  // 移除末尾的斜杠以统一格式
  const normalizedTargetPath = targetPath.replace(/\/$/, "")

  return RoutePaths.some((path) => {
    const routePath = path.replace(/\/$/, "")
    // 创建更灵活的路径匹配模式
    const pattern = routePath
      .replace(/:[^/]+/g, "[^/]+") // 处理 params 参数
      .replace(/\//g, "\\/") // 转义斜杠

    const pathRegex = new RegExp(`^${pattern}$`)
    return pathRegex.test(normalizedTargetPath)
  })
}

// 获取属于独立路由的所有项
export function collectInnerLinkRoutes(routes: RouteRecordRaw[], ResourceRoutePath: { [propNmae: string]: string[] }, RouteTitleMap: { [propNmae: string]: string }, parentName?: string) {
  routes.forEach((item) => {
    item.name && (RouteTitleMap[item.name] = item.meta?.title)
    // 如果存在父路由名称，添加当前路由路径
    if (parentName) {
      if (!ResourceRoutePath[parentName]) {
        ResourceRoutePath[parentName] = []
      }
      if (!ResourceRoutePath[parentName].includes(item.path)) {
        ResourceRoutePath[parentName].push(item.path)
      }
    }
    // 如果当前路由是内部链接且具有名称
    if (item.meta?.isInnerLink && item.name) {
      const currentName = item.name as string
      if (!ResourceRoutePath[currentName]) {
        ResourceRoutePath[currentName] = []
      }
      if (!ResourceRoutePath[currentName].includes(item.path)) {
        ResourceRoutePath[currentName].push(item.path)
      }
      // 递归时，将当前路由作为父路由
      if (item.children && item.children.length > 0) {
        collectInnerLinkRoutes(item.children, ResourceRoutePath, RouteTitleMap, currentName)
      }
    } else if (item.children && item.children.length > 0) {
      // 如果没有更改 parentName，则继续递归
      collectInnerLinkRoutes(item.children, ResourceRoutePath, RouteTitleMap, parentName)
    }
  })
}